<template>
  <div class="h-full flex flex-col bg-white">
    <!-- 顶部工具栏 -->
    <div class="px-4 py-2 border-b border-gray-100">
      <!-- 搜索框 -->
      <div class="mb-2">
        <el-input
          v-model="searchQuery"
          placeholder="搜索变量名、类型或值..."
          size="small"
          clearable
          prefix-icon="el-icon-search"
          @input="handleSearchInput"
        >
          <el-select
            v-model="searchType"
            slot="prepend"
            placeholder="搜索类型"
            style="width: 90px"
            size="small"
          >
            <el-option label="全部" value="all"></el-option>
            <el-option label="名称" value="name"></el-option>
            <el-option label="类型" value="type"></el-option>
            <el-option label="值" value="value"></el-option>
          </el-select>
        </el-input>
      </div>

      <!-- 操作按钮 -->
      <div class="flex items-center justify-between">
        <!-- 搜索结果统计 -->
        <div v-if="searchQuery" class="text-xs text-gray-500">
          找到 <span class="font-semibold text-primary-500">{{ filteredVariables.length }}</span> 个匹配项
        </div>
        <div v-else class="text-xs text-gray-500">
          共 {{ localVariables.length }} 个变量
        </div>

        <!-- 工具按钮 -->
        <div class="flex gap-1">
          <el-button
            type="text"
            icon="el-icon-search"
            size="small"
            class="!text-primary-500 hover:!text-primary-600"
            @click="showEvaluateDialog"
            title="求值表达式"
          >
            求值
          </el-button>
          <el-button
            type="text"
            icon="el-icon-refresh"
            size="small"
            class="!text-primary-500 hover:!text-primary-600"
            :loading="loading"
            @click="handleRefresh"
          >
            刷新
          </el-button>
        </div>
      </div>
    </div>

    <!-- 局部变量列表 -->
    <div class="flex-1 overflow-hidden">
      <div class="h-full overflow-y-auto py-2" v-loading="loading">
        <!-- 空状态 -->
        <div v-if="localVariables.length === 0 && !loading" class="flex flex-col items-center justify-center h-48 text-gray-400">
          <i class="el-icon-info text-5xl mb-2 opacity-50"></i>
          <p class="text-sm m-0">暂无局部变量</p>
        </div>

        <!-- 无搜索结果 -->
        <div v-else-if="searchQuery && filteredVariables.length === 0" class="flex flex-col items-center justify-center h-48 text-gray-400">
          <i class="el-icon-search text-5xl mb-2 opacity-50"></i>
          <p class="text-sm m-0">未找到匹配的变量</p>
          <p class="text-xs mt-1 text-gray-400">尝试修改搜索条件</p>
        </div>

        <!-- 变量列表 -->
        <div
          v-for="(variable, index) in displayVariables"
          :key="'local-' + index"
          class="px-4"
        >
          <variable-tree-node :variable="variable" :search-keyword="searchQuery" />
        </div>
      </div>
    </div>

    <!-- 求值对话框 -->
    <el-dialog
      title="求值表达式"
      :visible.sync="evaluateDialogVisible"
      width="700px"
      :append-to-body="true"
      :close-on-click-modal="false"
    >
      <!-- 表达式输入 -->
      <div class="mb-4">
        <label class="block text-sm text-gray-700 mb-2">表达式</label>
        <el-input
          v-model="evaluateExpression"
          placeholder="请输入Go表达式，例如：myVar, len(mySlice), myStruct.field"
          @keyup.enter.native="handleEvaluate"
        />
      </div>

      <!-- 最大深度设置 -->
      <div class="mb-4">
        <label class="block text-sm text-gray-700 mb-2">
          最大深度
          <span class="text-gray-400 text-xs ml-1">(递归展开层数)</span>
        </label>
        <el-slider
          v-model="evaluateMaxDepth"
          :min="1"
          :max="15"
          :marks="{ 1: '1', 5: '5', 10: '10', 15: '15' }"
          show-input
          :show-input-controls="false"
          input-size="small"
        />
        <div class="text-xs text-gray-500 mt-1">
          当前深度：{{ evaluateMaxDepth }} 层
          <span v-if="evaluateMaxDepth > 10" class="text-orange-500 ml-2">
            ⚠️ 深度较高可能导致求值较慢
          </span>
        </div>
      </div>

      <!-- 求值按钮 -->
      <div class="mb-4">
        <el-button
          type="primary"
          icon="el-icon-check"
          @click="handleEvaluate"
          :loading="evaluating"
          block
        >
          {{ evaluating ? '求值中...' : '求值' }}
        </el-button>
      </div>

      <!-- 结果显示区域 -->
      <div v-if="evaluateResult" class="mt-4 p-4 bg-gray-50 rounded border border-gray-200 max-h-96 overflow-y-auto">
        <div class="flex items-center justify-between mb-2">
          <div class="text-sm font-medium text-gray-700">结果：</div>
          <el-button
            type="text"
            size="small"
            icon="el-icon-delete"
            @click="clearEvaluateResult"
            class="!text-gray-400 hover:!text-gray-600"
          >
            清除
          </el-button>
        </div>
        <variable-tree-node :variable="evaluateResult" />
      </div>

      <!-- 空状态 -->
      <div v-else class="mt-4 p-8 bg-gray-50 rounded border border-gray-200 flex flex-col items-center justify-center text-gray-400">
        <i class="el-icon-info text-4xl mb-2 opacity-50"></i>
        <p class="text-sm m-0">输入表达式并点击求值查看结果</p>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="evaluateDialogVisible = false">关闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import VariableTreeNode from './VariableTreeNode.vue'

export default {
  name: 'VariablePanel',
  components: {
    VariableTreeNode
  },
  props: {
    localVariables: {
      type: Array,
      default: () => []
    },
    loading: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      searchQuery: '',
      searchType: 'all',  // all | name | type | value
      evaluateDialogVisible: false,
      evaluateExpression: '',
      evaluateMaxDepth: 3,  // 默认深度3层（与设置中的局部变量深度一致）
      evaluateResult: null,
      evaluating: false  // 求值中的加载状态
    }
  },
  computed: {
    // 过滤后的变量列表
    filteredVariables() {
      if (!this.searchQuery) {
        return this.localVariables
      }

      const query = this.searchQuery.toLowerCase()
      return this.filterVariables(this.localVariables, query)
    },

    // 显示的变量列表
    displayVariables() {
      return this.filteredVariables
    }
  },
  methods: {
    // 递归过滤变量（包括子变量）
    filterVariables(variables, query) {
      const results = []

      for (const variable of variables) {
        const matchResult = this.matchVariable(variable, query)

        if (matchResult.matched) {
          // 如果当前变量匹配，包含它及其所有子变量
          results.push(variable)
        } else if (matchResult.hasMatchingChildren) {
          // 如果子变量匹配，创建一个只包含匹配子变量的副本
          const filteredChildren = this.filterVariables(variable.children || [], query)
          if (filteredChildren.length > 0) {
            results.push({
              ...variable,
              children: filteredChildren
            })
          }
        }
      }

      return results
    },

    // 检查变量是否匹配搜索条件
    matchVariable(variable, query) {
      let matched = false
      let hasMatchingChildren = false

      // 根据搜索类型进行匹配
      if (this.searchType === 'all' || this.searchType === 'name') {
        if (variable.name && variable.name.toLowerCase().includes(query)) {
          matched = true
        }
      }

      if (this.searchType === 'all' || this.searchType === 'type') {
        if (variable.type && variable.type.toLowerCase().includes(query)) {
          matched = true
        }
      }

      if (this.searchType === 'all' || this.searchType === 'value') {
        const value = this.getVariableValueString(variable)
        if (value && value.toLowerCase().includes(query)) {
          matched = true
        }
      }

      // 检查子变量是否匹配
      if (!matched && variable.children && variable.children.length > 0) {
        for (const child of variable.children) {
          const childResult = this.matchVariable(child, query)
          if (childResult.matched || childResult.hasMatchingChildren) {
            hasMatchingChildren = true
            break
          }
        }
      }

      return { matched, hasMatchingChildren }
    },

    // 获取变量值的字符串表示
    getVariableValueString(variable) {
      if (variable.value !== undefined && variable.value !== null) {
        return String(variable.value)
      }
      return ''
    },

    // 搜索输入处理
    handleSearchInput() {
      // 搜索逻辑在 computed 中自动处理
    },

    // 刷新处理
    handleRefresh() {
      this.searchQuery = ''  // 清空搜索
      this.$emit('refresh')
    },

    showEvaluateDialog() {
      this.evaluateExpression = ''
      this.evaluateResult = null
      this.evaluateMaxDepth = 3  // 重置为默认深度（与设置一致）
      this.evaluating = false
      this.evaluateDialogVisible = true
    },

    handleEvaluate() {
      if (!this.evaluateExpression.trim()) {
        this.$message.warning('请输入表达式')
        return
      }

      this.evaluating = true
      this.$emit('evaluate', {
        expression: this.evaluateExpression,
        maxDepth: this.evaluateMaxDepth
      })
    },

    clearEvaluateResult() {
      this.evaluateResult = null
    }
  }
}
</script>

<style scoped>
/* 修复滑块刻度标签宽度问题 */
:deep(.el-slider__marks-text) {
  white-space: nowrap;
  min-width: 20px;
  text-align: center;
}

/* 确保对话框内的滑块有足够空间 */
.el-dialog >>> .el-slider {
  padding-left: 10px;
  padding-right: 10px;
}
</style>
